//
//  NetworkTools.swift
//  04-AFNetworking封装
//
//  Created by haoran on 16/4/28.
//  Copyright © 2016年 xuhaoran. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType :String {
    case GET
    case POST
}

class NetworkTools: AFHTTPSessionManager {
    // 1.将NetworkingTools设置成单例
    static let shareInstance : NetworkTools =  {
        let tools = NetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        return tools
    }()

}

// MARK:- 封装网络请求
extension NetworkTools {

    func request( type: RequestType, urlString : String, parameters: [String : AnyObject], finished:(response : AnyObject? , error : NSError?)->()) {
        
        //1.定义成功后的闭包
        let successCallBack = { (task : NSURLSessionTask , result : AnyObject?) -> Void in
            finished(response: result , error: nil)
        }
        
        //2.定义失败后的闭包
        let failureCallBack = { (task : NSURLSessionTask? , error : NSError) -> Void in
            finished(response: nil , error: error)
        }

        //3.发送网络请求
        switch type {
        case .GET:
            GET(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        case .POST:
            POST(urlString, parameters: parameters, progress: nil, success:successCallBack , failure: failureCallBack)
        }
    }
}

// MARK:- 请求主页数据
extension NetworkTools {

    func loadHomeData(offSet : Int ,finished : (response : [[String : AnyObject]]?, error : NSError?)-> Void){
        
        // 1.获得请求数据URL
        let urlString = "http://mobapi.meilishuo.com/2.0/twitter/popular.json"
        
        // 2.获取请求参数
        let parameters = [
            "offset" : "\(offSet)",
            "limit" : "30",
            "page" : "1",
            "access_token" : "b92e0c6fd3ca919d3e7547d446d9a8c2"
        ]
        
        request(.GET, urlString: urlString, parameters: parameters) { (response, error) in
        
            // 1.判断是否有误
            if error != nil{
                finished(response: nil, error: error)
            }
            
            
            // 2.获取结果
            guard let responses = response as? [String : AnyObject] else {
                finished(response: nil, error: NSError(domain: "data error", code: -1011, userInfo: nil))
                return
            }
        
            // 3.回调数据
            finished(response: responses["data"] as? [[String : AnyObject]], error: nil)
        }
    }

}


 
